package com.unitd.base.module.logistics.controller;

import com.google.common.collect.Maps;
import com.unitd.base.frame.enums.ResultEnum;
import com.unitd.base.frame.exception.LogisticsException;
import com.unitd.base.frame.plugins.module.controller.BaseController;
import com.unitd.base.frame.spring.result.AjaxResult;
import com.unitd.base.frame.utils.StringUtils;
import com.unitd.base.module.logistics.service.BatchExpressFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * 文件上传、下载前端控制器
 * @filename FileDealWithController.java
 * @copyright www.unitd.com
 * @author hudan
 * @version 1.0
 * @date 2019-02-01
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileDealWithController extends BaseController {

	@Autowired
	private BatchExpressFileService batchExpressFileService;

	/**
	 * 实现将需要进行批量查询的excel文件的上传功能
	 * 上传excel文件,并根据excel文件内容读取数据库或者调用接口,获取相应快递的物流详情后,将数据写入excel文件后,反馈给前端
	 * @param file 需要进行批量查询的excel文件
	 * @return 响应结果
	 */
	@PostMapping(value = "/fileUpload")
	public AjaxResult singleFileUpload(@RequestParam("file") MultipartFile file) {

		try {
			String fileName = file.getOriginalFilename();
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
			log.info("得到的上传文件的文件内容为:{}", fileType);
//			File fileDir = new File(FileUtils.getJarRootPath(), "data/upload");
			File fileDir = new File("data/upload");
			if (!fileDir.exists()) {
				fileDir.mkdir();
			}
			log.info("得到上传文件存储的绝对路径为:{}", fileDir.getAbsolutePath());

			// 将上传得到的文件保存到本地
			File importFile = new File(fileDir.getAbsolutePath(), fileName);
			file.transferTo(importFile);

			// 读取得到的上传文件,并根据文件内容调用相应的接口获取相应的物流信息后,将内容写入新文件
			File exportFile = batchExpressFileService.importAndDealWithExcel(importFile);

			Map<String, String> fileMap = Maps.newHashMap();
			fileMap.put("exportFile", exportFile.getAbsolutePath());
			fileMap.put("fileName", exportFile.getName());

			return new AjaxResult(fileMap);
		} catch (IOException e) {
			throw new LogisticsException(ResultEnum.UPLOAD_FILE_ERROR);
		}
	}

	/**
	 * @return 响应结果
	 * 实现上传需要查询的文件后的下载功能
	 */
	@RequestMapping(value = "/fileDownLoad")
	public AjaxResult downloadFile(@RequestParam Map<String, Object> reqParam, HttpServletResponse response) {

		// 获取需要下载的文件名称
		String fileName = (String) reqParam.get("fileName");

		if (!StringUtils.isNull(fileName)) {

			// 上传文件的存储路径
			File fileDir = new File("data/upload");
			File file = new File(fileDir + File.separator + fileName);
			if (file.exists()) {
				// 设置强制下载不打开
				response.setContentType("application/force-download");
				// 设置文件名
				response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);

				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
					System.out.println("success");
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return null;
	}
}